package com.yxhl.zoume.core.func.pay.presenter;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.yxhl.zoume.BuildConfig;
import com.yxhl.zoume.R;
import com.yxhl.zoume.ZMConfig;
import com.yxhl.zoume.common.presenter.BasePresenter;
import com.yxhl.zoume.common.presenter.IPresenter;
import com.yxhl.zoume.common.ui.view.BaseView;
import com.yxhl.zoume.core.car.model.PayResultEvent;
import com.yxhl.zoume.core.car.model.StatusEnum;
import com.yxhl.zoume.core.func.pay.model.PayResult;
import com.yxhl.zoume.core.func.pay.model.event.PaymentSuccessfulEvent;
import com.yxhl.zoume.core.func.pay.view.AliPayView;
import com.yxhl.zoume.data.DataConstants;
import com.yxhl.zoume.data.http.rest.param.pay.AliPaySignStrParam;
import com.yxhl.zoume.data.http.rest.response.pay.ALiPaySignStrResponse;
import com.yxhl.zoume.data.rxbus.RxBus;
import com.yxhl.zoume.domain.interactor.ZMSubscriber;
import com.yxhl.zoume.domain.interactor.pay.ALiPaySignStrUseCase;
import com.yxhl.zoume.utils.LOG;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;

import javax.inject.Inject;

/**
 * Created by vhawk on 16/3/31.
 */
public class AliPayPresenter extends BasePresenter implements IPresenter {

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;

    private ALiPaySignStrUseCase useCase;
    private AliPayView aliPayView;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        RxBus.getInstance().send(new PaymentSuccessfulEvent());
                        aliPayView.renderAliPaySucceed();
                        RxBus.getInstance().send(new PayResultEvent(StatusEnum.STATUS_ENUM_TRUE));
//                         支付成功跳转行程管理，并关闭当前activity
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
//                            AlertUtil.showShortSimpleAlert(context, mFragment.getActivity().getString(R.string.pay_result_comfirming));
                            aliPayView.renderAliPayFailure(payResult.getResult());
                            RxBus.getInstance().send(new PayResultEvent(StatusEnum.STATUS_ENUM_UNKNOWN));
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
//                            AlertUtil.showShortSimpleAlert(context, context.getString(R.string.pay_failure));
                            if (TextUtils.isEmpty(payResult.getResult())) {
                                aliPayView.renderAliPayFailure("支付宝支付失败");
                            } else {
                                aliPayView.renderAliPayFailure(payResult.getResult());
                            }
                            RxBus.getInstance().send(new PayResultEvent(StatusEnum.STATUS_ENUM_FALSE));
                        }
                    }

                    break;
                }
                case SDK_CHECK_FLAG: {

                    break;
                }
                default:
                    break;
            }
        }
    };

    @Inject
    public AliPayPresenter(Context context, ALiPaySignStrUseCase useCase) {
        super(context);
        this.useCase = useCase;
    }

    @Override
    public void onResume() {

    }

    @Override
    public void onPause() {

    }

    @Override
    public void onDestroy() {
        useCase.unsubscribe();
    }

    @Override
    public void attachView(BaseView view) {
        this.aliPayView = (AliPayView) view;
    }

    /**
     * 获取支付宝支付用的签证字符串
     *
     * @param context
     * @param totalFee
     * @param ticketOrderId
     */
    public void getSignedStr(final Context context, String totalFee, String ticketOrderId) {

        getSignedStr(context, totalFee, ticketOrderId, null, null);
//        String subject = context.getResources().getString(R.string.product_desc);
//        String body = context.getResources().getString(R.string.product_desc);
//        final String order = getOrderInfo(subject, body, totalFee, ticketOrderId);
//
//        AliPaySignStrParam param = new AliPaySignStrParam(getMobile(), getToken());
//        param.setSignSrc(order);
//        param.setId(ticketOrderId);
//        useCase.execute(param).subscribe(new ZMSubscriber<ALiPaySignStrResponse>() {
//            @Override
//            public void onNext(ALiPaySignStrResponse aLiPaySignStrResponse) {
//                super.onNext(aLiPaySignStrResponse);
//                if (true == aLiPaySignStrResponse.isSucc()) {
//                    pay(context, order, aLiPaySignStrResponse.getSign());
//                } else {
//                    aliPayView.renderAliPayFailure(aLiPaySignStrResponse.getResultMessage());
//                }
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                super.onError(e);
//                aliPayView.renderAliPaySignedError();
//            }
//        });
    }


    /**
     * 快车支付调用
     *
     * @param context
     * @param totalFee
     * @param ticketOrderId
     * @param couponUserRelId
     * @param disCountFee
     */
    public void getSignedStr(final Context context, String totalFee, String ticketOrderId, String couponUserRelId, String disCountFee) {
        String subject = context.getResources().getString(R.string.product_desc);
        String body = context.getResources().getString(R.string.product_desc);

        double actualFee;
        if (TextUtils.isEmpty(disCountFee)) {
            actualFee = Double.parseDouble(totalFee);
        } else {
            actualFee = Double.parseDouble(totalFee) - Double.parseDouble(disCountFee);
        }
        DecimalFormat df = new DecimalFormat("######0.00");
        final String order = getOrderInfo(subject, body, df.format(actualFee), ticketOrderId);

        AliPaySignStrParam param = new AliPaySignStrParam(getMobile(), getToken());
        param.setCouponUserRelId(couponUserRelId)
                .setDisCountFee(disCountFee);
        param.setSignSrc(order);
        param.setId(ticketOrderId);
        useCase.execute(param, new ZMSubscriber<ALiPaySignStrResponse>() {
            @Override
            public void onNext(ALiPaySignStrResponse aLiPaySignStrResponse) {
                super.onNext(aLiPaySignStrResponse);
                if (true == aLiPaySignStrResponse.isSucc()) {
                    pay(context, order, aLiPaySignStrResponse.getSign());
                } else {
                    aliPayView.renderAliPayFailure(aLiPaySignStrResponse.getResultMessage());
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                aliPayView.renderAliPaySignedError();
            }
        });
    }

    /**
     * 充值
     * "YXHL_RECHARGE"
     *
     * @param context
     * @param totalFee
     */
    public void getAliRechargeSignedStr(final Context context, String totalFee) {
        String subject = "走么充值";
        String body = "走么充值";
        final String order = getOrderInfo(subject, body, totalFee, "YXHL_RECHARGE");
        AliPaySignStrParam param = new AliPaySignStrParam(getMobile(), getToken());
        param.setBizType(6)
                .setClientVersion(BuildConfig.VERSION_NAME)
                .setTotalFee(totalFee)
                .setSignSrc(order);
        useCase.execute(param, new ZMSubscriber<ALiPaySignStrResponse>() {
            @Override
            public void onNext(ALiPaySignStrResponse aLiPaySignStrResponse) {
                super.onNext(aLiPaySignStrResponse);
                if (true == aLiPaySignStrResponse.isSucc()) {
                    pay(context, aLiPaySignStrResponse.getOrdSgin(), aLiPaySignStrResponse.getSign());
                } else {
                    aliPayView.renderAliPayFailure(aLiPaySignStrResponse.getResultMessage());
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                aliPayView.renderAliPaySignedError();
            }
        });
    }


    private void pay(final Context context, String orderInfo, String signedStr) {
        final String payInfo;

        try {
            // 完整的符合支付宝参数规范的订单信息

            String mytext = java.net.URLEncoder.encode(signedStr, "utf-8");

            payInfo = new String((orderInfo + "&sign=\"" + mytext + "\"&"
                    + getSignType()).getBytes(), "utf-8");

            LOG.v("vhawk", "alipay info");

            LOG.v("vhawk", payInfo);

            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    // 构造PayTask 对象
                    PayTask alipay = new PayTask((Activity) context);
                    // 调用支付接口，获取支付结果
                    String result = alipay.pay(payInfo);

                    LOG.v("vhawk", "result = " + result);
                    LOG.v("vhawk", "code = " + SDK_PAY_FLAG);

                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };

            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            aliPayView.renderAliPaySignedError();
        }

    }


    /**
     * get the sign type we use. 获取签名方式
     */
    public String getSignType() {
        return "sign_type=\"RSA\"";
    }

    /**
     * create the order info. 创建订单信息
     */
    public String getOrderInfo(String subject, String body, String price, String orderId) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + ZMConfig.ALI_PAY_PARTNER + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + ZMConfig.ALI_PAY_SELLER + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + orderId + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + DataConstants.BASE_URL + "/notify/aliasyncpay"
                + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
//        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
//        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

}
